<template>
  <div class="infoConfig">
    <el-form ref="form" :model="form" :rules="rules">
      <div class="leftLine title">机构信息</div>
      <el-select v-if="pageType == 'add'" v-model="orgBaseInfo.orgName" placeholder="请选择机构">
        <el-option
          v-for="item in options"
          :key="item.orgId"
          :label="item.orgName"
          :value="item.orgName"
          @click.native="deptIdClick(item.orgId)"
        />
      </el-select>
      <el-row v-if="pageType == 'seeInfo' || pageType == 'edit'">
        <el-col :span="4">机构</el-col>
        <el-col :span="7">{{ orgBaseInfo.orgName }}</el-col>
        <el-col :span="4">业务编号</el-col>
        <el-col :span="7">{{ orgBaseInfo.orgId }}</el-col>
      </el-row>
      <div class="leftLine title">
        商户套餐配置

      </div>
      <div style="color:#828282">*套餐等级从高到低按照数字正序排列</div>
      <div class="SetMealBox">
        <span
          v-for="(item,index) in setMealArr"
          :key="index"
          :class="{active:activeItem.name === item.name}"
          @click="selected(item, index)"
        >{{ item.name }}</span>
      </div>
      <el-button v-if=" ['edit', 'add'].includes(pageType)" type="text" @click="addLine">添加套餐</el-button>
      <p v-show="activeItem.name === '交互次数套餐'" class="SetMealBox-remarks">注:针对当前商户套餐增加交互次数,不影响套餐有效期;商户无套餐或者无限交互次数套餐不可购买;</p>
      <!-- <el-form-item label="" prop="config"> -->
      <AddList v-model="baseListData" :show-add-btn="false" :show-del-btn="false">
        <template v-slot="{item: { item, index }}">
          <el-form-item :label="'套餐'+(index+1)" label-width="80px" class="listItem" :prop="'config'+index">
            <div class="content">
              <div>
                <el-row :gutter="20">
                  <el-col :span="4">套餐名称</el-col>
                  <el-col :span="7">
                    <el-input v-model="item.tempName" :disabled="pageType == 'seeInfo'" class="numInput" :maxlength="10" size="small" />
                  </el-col>
                  <el-col :span="4">排序</el-col>
                  <el-col :span="7">
                    <el-input v-model="item.queueFlag" :disabled="pageType == 'seeInfo'" class="numInput" size="small" />
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="4">交互次数</el-col>
                  <el-col :span="15">
                    <el-input
                      v-if="item.restrictFlag == 1"
                      placeholder="不限"
                      disabled
                      class="numInput"
                      size="small"
                    />
                    <el-input-number
                      v-else
                      v-model="item.monthFlow"
                      :precision="0"
                      :min="1"
                      :controls="false"
                      :max="999"
                      :disabled="pageType == 'seeInfo'"
                      class="numInput"
                      size="small"
                    />
                    万次
                    <el-checkbox
                      v-if="activeItem.name != '交互次数套餐' && pageType != 'seeInfo'"
                      v-model="item.restrictFlag"
                      class="mg-l-20"
                      true-label="1"
                      false-label="0"
                      text-color="#ffb72f"
                      @change="(val) => checkboxChange(val, item)"
                    >不限交互次数
                    </el-checkbox>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="4">价格</el-col>
                  <el-col :span="15">
                    <el-input-number v-model="item.price" :precision="0" :min="0" :controls="false" :disabled="pageType == 'seeInfo'" class="numInput" size="small" />
                    流量余额
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="4">适用商户</el-col>
                  <el-col :span="11">
                    <el-radio-group v-model="item.mercScope">
                      <el-radio label="0">全部商户</el-radio>
                      <el-radio label="1">指定商户</el-radio>
                    </el-radio-group>
                    <div v-show="item.mercScope == '1'">
                      <span class="tipText">请输入商户编号，多个请换行输入</span>
                      <el-input
                        v-model="item.pkgSpecificListStr"
                        :disabled="pageType == 'seeInfo'"
                        type="textarea"
                        size="small"
                        :autosize="{ minRows: 1, maxRows: 4}"
                      />
                    </div>
                  </el-col>
                </el-row>
                <!-- <el-row v-if="item.restrictFlag == 1" :gutter="20">
                  <el-col :span="4">多门店加租</el-col>
                  <el-col :span="15">
                    <el-input v-model="item.addRentRatio" class="numInput" size="small" />%
                  </el-col>
                </el-row> -->
              </div>
              <el-button v-if="pageType == 'add' || pageType == 'edit'" type="text" @click="delLine(item, index)">删除</el-button>

            </div>
          </el-form-item>
        </template>
      </AddList>
      <!-- </el-form-item> -->
      <div class="btnList textCenter">
        <el-button v-if="pageType == 'edit'||pageType == 'add'" size="small" @click="$emit('close')">取消</el-button>
        <el-button v-if="pageType == 'edit'||pageType == 'add'" type="primary" size="small" @click="submit">保存配置
        </el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import {
  merchantConfUpdate,
  mrcDeptList,
  merchantConfInsert
} from '@/api/flowConf'
import AddList from '@/components/AddList/index.vue'

export default {
  components: {
    AddList
  },
  props: {
    infoConfig: {}
  },
  data() {
    return {
      setMealArr: {
        // 对应后端type keyStr： 0：月套餐；1：年套餐；2：交互套餐；3：季套餐；4：半年套餐
        month: { name: '月套餐', keyStr: 0, key: 'month', list: [] },
        season: { name: '季套餐', keyStr: 3, key: 'season', list: [] },
        halfYear: { name: '半年套餐', keyStr: 4, key: 'halfYear', list: [] },
        year: { name: '年套餐', keyStr: 1, key: 'year', list: [] },
        interactive: { name: '交互次数套餐', keyStr: 2, key: 'interactive', list: [] }
      },
      activeItem: { name: '月套餐', keyStr: 0, key: 'month', list: [] },
      form: {},
      orgBaseInfo: {},
      merchantPackageConfs: [],
      options: [],
      value: ''
    }
  },
  computed: {
    baseListData() {
      // 列表展示数据源  区分这个是因为已经保存过的数据，在删除时 需要把flag改成3，然后依然将这条数据传递给接口
      return this.merchantPackageConfs.filter(v => v.flag != 3)
    },
    pageType() {
      return this.infoConfig.type
    },
    rules() {
      const obj = {}
      this.merchantPackageConfs.forEach((item, idx) => {
        obj['config' + idx] = [{
          validator: this.validForm,
          trigger: 'change'
        }]
      })
      return obj
    }
  },
  mounted() {
    if (this.infoConfig.data) {
      this.initBaseConfig()
    }
    this.getMrcDeptList()
  },

  methods: {
    // 初始化基础数据
    initBaseConfig() {
      this.orgBaseInfo = JSON.parse(JSON.stringify(this.infoConfig.data))
      Object.values(this.setMealArr).forEach(meal => {
        const dataArr = this.orgBaseInfo[meal.key + 'Arr']
        if (dataArr && dataArr.length) {
          meal.list = dataArr.map(item => {
            return {
              ...item,
              flag: item.flag || 2,
              monthFlow: item.restrictFlag === '1' ? '不限' : item.monthFlow
            }
          })
        }
      })
      console.log('initBaseConfig', this.orgBaseInfo, this.setMealArr)
      this.activeItem = this.setMealArr['month']
      this.merchantPackageConfs = this.setMealArr['month']['list']
    },
    deptIdClick(id) {
      this.$set(this.orgBaseInfo, 'orgId', id)
      // console.log('赋值', this.$set(this.orgBaseInfo, 'orgId', id))
    },
    // 获取未配置商户流量的机构列表
    getMrcDeptList() {
      mrcDeptList().then(res => {
        // console.log('获取未配置商户流量的机构列表', res)
        if (res.succeed) {
          this.options = res.data
        }
      })
    },
    // 点击切换
    selected(item, index) {
      this.activeItem = item
      this.merchantPackageConfs = item.list
    },
    submit() {
      delete this.orgBaseInfo.monthArr
      delete this.orgBaseInfo.yearArr
      delete this.orgBaseInfo.superposition

      if (!this.orgBaseInfo.orgName) {
        this.$message.error('请选择一个机构')
        return
      }
      this.$refs['form'].validate((valid) => {
        if (valid) {
          // 校验是否有重复的套餐名称
          // console.log('this.merchantPackageConfs', this.merchantPackageConfs)

          const setData = new Set(this.baseListData.map(item => item.price * 1))
          if (setData.size != this.baseListData.length) {
            this.$message.error('请勿输入相同套餐价格')
            return
          }
          const subArr = []
          // 循环所有套餐类型
          Object.values(this.setMealArr).forEach(meal => {
            // 循环该类型下所有套餐
            meal.list.forEach(item => {
              subArr.push({
                ...item,
                price: item.price * 1,
                // mercScope 为0  传空数组给接口
                pkgSpecificList: item.mercScope == '0' ? [] : item.pkgSpecificListStr.split('\n').filter(v => !!v),
                monthFlow: item.restrictFlag == 1 ? 0 : this.$math.mul(item.monthFlow, 10000)
              })
            })
          })

          // const checkMonthArr = finalMonthArr.filter(el => {
          //   return el.flag != 3
          // })

          // const checkYearArr = finalYearArr.filter(el => {
          //   return el.flag != 3
          // })

          console.log('最终提交数组', subArr)
          if (this.pageType === 'add') {
            console.log('提交的类型是新增')
            // if (this.monthArr.length === 0 && this.yearArr.length === 0) {
            //   this.$message.error('请至少配置一个月/年套餐!')
            //   return
            // }
            merchantConfInsert({
              orgBaseInfo: this.orgBaseInfo,
              merchantPackageConfs: subArr
            }).then(res => {
              this.$message.success('操作成功！')
              this.$emit('sucClose')
            })
          } else {
            console.log('提交的类型是修改')
            // if (checkMonthArr.length === 0 && checkYearArr.length === 0) {
            //   this.$message.error('请至少配置一个月/年套餐!')
            //   return
            // }
            merchantConfUpdate({
              orgBaseInfo: this.orgBaseInfo,
              merchantPackageConfs: subArr
            }).then(res => {
              this.$message.success('操作成功！')
              this.$emit('sucClose')
            })
          }
        } else {
          this.$message.error('表单信息填写有误，请重新检查！')
          return false
        }
      })
    },
    validForm(rule, value, callback) {
      const { field } = rule
      console.log('rule', rule)
      let text = ''
      // 租户交互次数余额折扣配置
      if (this.baseListData.length) {
        this.baseListData.forEach((item, index) => {
          if (field == 'config' + index) {
            const { queueFlag, monthFlow, restrictFlag, price, mercScope, pkgSpecificListStr } = item
            const _pkgSpecificListStr = pkgSpecificListStr.split('\n').filter(v => !!v)
            console.log('_pkgSpecificListStr', _pkgSpecificListStr)
            if (!queueFlag && queueFlag != '0') {
              text = `请输入排序字段`
            } else if (!monthFlow && restrictFlag == 0) {
              text = `请输入交互次数`
            } else if (!price) {
              text = `请输入价格`
            } else if (mercScope == '1' && !_pkgSpecificListStr.length) {
              text = `请输入商户编号`
            }
          }
        })
      } else {
        text = '至少填写一条配置'
      }
      text ? callback(text) : callback()
    },
    checkboxChange(val, data) {
      console.log()
      if (val == '1') {
        data.monthFlow = '不限'
        data.addRentRatio = 0
      } else {
        data.monthFlow = 0
        data.addRentRatio = 0
      }
    },
    // 新增
    addLine() {
      this.merchantPackageConfs.push({
        'addRentRatio': 0,
        'monthFlow': 0,
        'price': 0,
        'queueFlag': '1',
        'restrictFlag': '0',
        'mercScope': '0',
        'pkgSpecificListStr': '',
        flag: 1,
        type: this.activeItem.keyStr
      })
    },
    // 删除一行
    delLine(item, index) {
      if (item.flag === 1) {
        this.merchantPackageConfs.splice(index, 1)
        console.log('新增删除')
      } else {
        item.flag = 3
        console.log('修改删除')
      }
    }

  }

}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .infoConfig {
    padding: 30px;

    .SetMealBox {
      margin: 20px 0;
      display: flex;
      cursor: pointer;
      span{
        margin-right: 30px;
      }

    }

    .SetMealBox-remarks {
      font-size: 12px;
    }

    .active {
      color: #FFB72F;
    }

    .btnList {
      margin-top: 50px;
    }
    .tipText{
      color: #AAAAAA;
      font-size: 12px;
      line-height: 20px;
    }
    .title {
      font-size: 15px;
      color: #000;
      margin: 30px 0;
    }

    .numInput {
      width: 150px;
      max-width: 100%;
      margin: 0 10px;
    }

    .listItem {
      border: 1px solid rgba(255, 183, 47, 1);
      border-radius: 10px;
      padding: 10px 10px 20px;
      margin: 10px 0;

      .content {
        display: flex;
        align-items: center;

        div {
          flex: 1;
        }
      }
    }
  }
</style>
